package activity

import (
	"context"
	// "fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/internal/utils/errorhandler"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateActivityLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateActivityLogic {
	return &BackendCreateActivityLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateActivityLogic) BackendCreateActivity(in *promotion.ActivityInfo) (*promotion.BaseIDResp, error) {
	// logx.Infof("BackendCreateActivity : %+v ", in)

	if in.Name == nil || len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("promotion.activityNameRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var data model.PromotionActivity
	if in.Name != nil {
		data.Name = strings.TrimSpace(*in.Name)

		filterMap := make(map[string]map[string][]any)
		filterMap[model.PromotionActivityColumns.Name] = map[string][]any{
			"equalTo": {data.Name},
		}
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"notIn": {globalkey.StatusDeleted, globalkey.StatusFinished, globalkey.StatusInvalid},
		}
		_, count, err := l.svcCtx.Activity.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("promotion.activityAlreadyExists")
		}
	}

	if in.Slug != nil {
		data.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.Desc != nil {
		data.Description = *in.Desc
	}
	if in.FilteredDesc != nil {
		data.DescriptionFiltered = *in.FilteredDesc
	}
	if in.MemberRestriction != nil && len(*in.MemberRestriction) > 0 {
		members := strings.Split(*in.MemberRestriction, ",")
		var newMembers []string
		for _, member := range members {
			newMember := strings.TrimSpace(member)
			if len(newMember) > 0 {
				newMembers = append(newMembers, strings.ToLower(newMember))
			}
		}
		if len(newMembers) > 0 {
			data.MemberRestriction = strings.Join(newMembers, ",")
		}
	}

	if in.MutexType != nil {
		data.MutexType = uint8(*in.MutexType)
	}
	if in.TimesLimit != nil {
		data.TimesLimit = uint8(*in.TimesLimit)
	}
	if in.Sort != nil {
		data.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		data.Status = uint16(*in.Status)
	} else {
		data.Status = uint16(globalkey.StatusDisabled)
	}
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			data.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			data.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}
	data.CreatedAt = time.Now()
	data.UpdatedAt = time.Now()
	data.CreateStep = enum.PromotionActivityStepBasic

	rel := &model.PromotionActivityRel{}
	if len(in.Meta) > 0 {
		for _, v := range in.Meta {
			if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
				continue
			}

			if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
				continue
			}

			rel.Meta = append(rel.Meta, &model.PromotionActivityMetum{
				MetaKey:   strings.TrimSpace(*v.Key),
				MetaValue: null.StringFrom(strings.TrimSpace(*v.Value)),
			})
		}
	}

	allMediaMap := make(map[string]string)
	if len(in.AllMedia) > 0 {
		for _, v := range in.AllMedia {
			if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
				allMediaMap[*v.Id] = *v.Url
			}
		}
	}

	if len(in.NewMedia) > 0 {
		var thumbnailOrder uint
		var thumbnailId uint64
		var thumbnailUrl string
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
				url = *v.Url
			}
			var uri string
			if v.Uri != nil && len(*v.Uri) > 0 {
				uri = *v.Uri
				if len(url) == 0 {
					url = uri
				}
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			metaData := strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			media := &model.PromotionAttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			}

			if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
				if uri, ok := allMediaMap[*v.Id]; ok {
					media.AttachmentSource = uri
				}
			}

			rel.Media = append(rel.Media, media)

			if thumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > order) {
				thumbnailOrder = order
				thumbnailId = mediaId
				thumbnailUrl = url
			}
		}

		if len(thumbnailUrl) > 0 {
			rel.Meta = append(rel.Meta, &model.PromotionActivityMetum{
				MetaKey:   "_thumbnail_id",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
			})
			rel.Meta = append(rel.Meta, &model.PromotionActivityMetum{
				MetaKey:   "_thumbnail_url",
				MetaValue: null.StringFrom(thumbnailUrl),
			})
		}
	}

	if in.ActivityType != nil {
		data.ActivityType = uint8(*in.ActivityType)

		switch data.ActivityType {
		case enum.PromotionActivityDiscount, enum.PromotionActivityMember, enum.PromotionActivityCharge:
			if in.ScopeType != nil {
				data.ScopeType = uint8(*in.ScopeType)
			}
			if in.GroupMode != nil {
				data.GroupMode = uint8(*in.GroupMode)
			}
			if in.GroupType != nil {
				data.GroupType = uint8(*in.GroupType)
			}
			if len(in.Groups) > 0 {
				groups, err := l.ParseDiscountRuleGroup(in.GroupMode, in.Groups)
				if err != nil {
					return nil, err
				}

				rel.Groups = groups
			}
		case enum.PromotionActivitySeckill:
			if in.SeckillLimit != nil {
				data.SeckillLimit = uint8(*in.SeckillLimit)
			}
			if in.SeckillCancelDuration != nil {
				data.SeckillCancelDuration = uint8(*in.SeckillCancelDuration)
			}
			if in.SeckillNotifyDuration != nil {
				data.SeckillNotifyDuration = uint8(*in.SeckillNotifyDuration)
			}
		case enum.PromotionActivityPackage:
			if in.PackageType != nil {
				data.PackageType = uint8(*in.PackageType)
			}
			if in.PackagePicId != nil {
				data.PackagePicID = *in.PackagePicId
			}
			if in.PackagePicUrl != nil {
				data.PackagePicURL = strings.TrimSpace(*in.PackagePicUrl)
			}
		default:
			return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
		}
	}

	// logx.Infof("BackendCreateActivity rel : %+v ", rel)

	err = l.svcCtx.Activity.Insert(l.ctx, tx, &data, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &promotion.BaseIDResp{
		Id:  data.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}

func (l *BackendCreateActivityLogic) ParseDiscountRuleGroup(
	mode *uint32,
	groups []*promotion.ActivityRuleGroupInfo,
) (groupRels []*model.PromotionRuleGroupRel, err error) {
	if mode == nil {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	for idx, v := range groups {
		var group model.PromotionRuleGroup
		if v.Threshold != nil {
			switch uint8(*mode) {
			case enum.PromotionActivityRuleGroupAmount:
				if i, err := moneyx.ParseAmount(*v.Threshold); err == nil && i > 0 {
					group.Threshhold = uint64(i)
				} else {
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			case enum.PromotionActivityRuleGroupNumber:
				if i, err := strconv.ParseInt(*v.Threshold, 10, 32); err == nil && i > 0 {
					group.Threshhold = uint64(i)
				} else {
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			default:
				return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
			}
		}
		if v.Sort != nil {
			group.Sort = uint16(*v.Sort)
		} else {
			group.Sort = uint16(idx + 1)
		}
		if v.Status != nil {
			group.Status = uint8(*v.Status)
		} else {
			group.Status = uint8(globalkey.StatusEnabled)
		}

		rules, err := l.ParseDiscountRule(v.Rules)
		if err != nil {
			return nil, err
		}

		groupRels = append(groupRels, &model.PromotionRuleGroupRel{
			Group: &group,
			Rules: rules,
		})
	}

	return
}

func (l *BackendCreateActivityLogic) ParseDiscountRule(
	rules []*promotion.ActivityRuleInfo,
) (list []*model.PromotionRule, err error) {
	if len(rules) > 0 {
		for idx, v := range rules {
			var rule model.PromotionRule

			if v.RuleType != nil {
				rule.RuleType = uint8(*v.RuleType)

				switch rule.RuleType {
				case enum.PromotionActivityRuleTypeDiscount:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)

						if v.Value != nil {
							switch rule.Mode {
							case enum.PromotionActivityRuleModeAmount:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.PromotionActivityRuleModeDiscount:
								if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 && i <= 100 {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.PromotionActivityRuleModeFixed:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							default:
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					}
				case enum.PromotionActivityRuleTypeFreeShipping:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)
					}

					if v.Regions != nil {
						rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
					}
				case enum.PromotionActivityRuleTypeExtraPoint:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.PromotionActivityRuleTypeCoupon:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				default:
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.Sort != nil {
				rule.Sort = uint16(*v.Sort)
			} else {
				rule.Sort = uint16(idx + 1)
			}
			if v.Status != nil {
				rule.Status = uint8(*v.Status)
			} else {
				rule.Status = uint8(globalkey.StatusEnabled)
			}

			list = append(list, &rule)
		}
	}

	return
}
